(function() {

    var cookieObject = {

        _addAttribute : function(name, value, buffer, encode) {
            if (encode) {
                name = encodeURIComponent(name);
                value = encodeURIComponent(value);
            }

            buffer.push(name);
            buffer.push('=');
            buffer.push(value);
            buffer.push(';');
        },

        get : function(name) {
            var cookiesString = document.cookie, cookiesMap = { };

            if ((typeof cookiesString != 'string') || (cookiesString.length == 0)) return null;

            var cookiesArray = cookiesString.split(/;\s/g);

            for (var i = 0; i < cookiesArray.length; ++i) {
                var currentCookie = cookiesArray[i].split('=');

                if (currentCookie.length == 2) {
                    cookiesMap[decodeURIComponent(currentCookie[0])] = decodeURIComponent(currentCookie[1]);
                }
            }

            if (typeof name == 'undefined') return cookiesMap;

            var
            result = cookiesMap[name],
            cookieExists = (typeof result != 'undefined');

            if (!cookieExists) return null;

            return result;
        },

        set : function(o) {
            var cookieStringBuffer = [];

            this._addAttribute(o.name, o.value, cookieStringBuffer, true);

            if (o.expires) {
                var expires = new Date((new Date()).getTime() + o.expires);
                this._addAttribute('expires', expires.toGMTString(), cookieStringBuffer);
            }

            if (o.path) this._addAttribute('path', o.path, cookieStringBuffer);

            if (o.domain) this._addAttribute('domain', o.domain, cookieStringBuffer);

            document.cookie = cookieStringBuffer.join('');
        }

    };

    juliet.registerModule('juliet.core', 'cookie', cookieObject);

})();
